#include<bits/stdc++.h>
using namespace std;

const int N = 2e5 + 10;
typedef pair<int, int> pii;

int n, m;
vector<pii> head[N];
int d[N];
int st[N];
int dijkstra(){
    priority_queue<pii, vector<pii>, greater<pii>> q;
    memset(d, 0x3f, sizeof d);
    d[1] = 0;
    q.push({d[1], 1});
    while(!q.empty()){
        pii temp = q.top();
        q.pop();
        int x = temp.second;
        if (!st[x]){  //主要是为了剪枝.
            st[x] = true;
            for (auto i : head[x]){
                int y = i.first;
                if (d[x] + i.second < d[y]){
                    d[y] = d[x] + i.second;
                    q.push({d[y], y});
                }
            }
        }
    }
    if (d[n] == 0x3f3f3f3f) return -1;
    return d[n];
}



int main(){
    cin >> n >> m;
    for (int i = 1; i <= m; i++){
        int a, b, c;
        cin >> a >> b >> c;
        head[a].push_back({b, c});
    }
    cout << dijkstra();
    return 0;
}